<?php

/**
 * emailPerformance actions.
 *
 * @package    ecrm
 * @subpackage emailPerformance
 * @author     Saul Santiago
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class emailPerformanceActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->emailCampaigns = Doctrine_Core::getTable('EmailCampaigns')
                            ->createQuery()
                            ->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
                            
    $this->filesToUpload = array(
      'selected' => array('dependencies' => array()),
      'hard_bounce' => array('dependencies' => array('selected')),
      'soft_bounce' => array('dependencies' => array('selected')),
      'opened' => array('dependencies' => array('hard_bounce', 'soft_bounce')),
      'clicked' => array('dependencies' => array('opened')),
      'clicked_details' => array('dependencies' => array('clicked')),
      'unsubscribed' => array('dependencies' => array('hard_bounce', 'soft_bounce')),
      'complaint' => array('dependencies' => array('hard_bounce', 'soft_bounce')),
    );
    
    $folderContents = scandir(getcwd().'/uploads');
    $this->folderFiles = array();
    foreach($folderContents as $folderContent) {
      if(is_file(getcwd().'/uploads/'.$folderContent)) {
        $this->folderFiles[] = $folderContent;
      }
    }
    
  }
  
  public function executeMapFields(sfWebRequest $request)
  {
    $this->forward404Unless($this->campaignId = $request->getParameter('campaign_id')); 
    //$files = $request->getFiles();
    $this->forward404Unless($this->fileType = $request->getParameter('file_type'));
    //$this->forward404Unless($this->file = $files['upload_file']);
    $this->fileName = $request->getParameter('file_name');
    //$upload = move_uploaded_file($this->file['tmp_name'], getcwd().'/uploads/'.$this->file['name']);
    //if($upload) {
      //$handle = fopen(getcwd().'/uploads/'.$this->file['name'], 'r');
      $handle = fopen(getcwd().'/uploads/'.$this->fileName, 'r');
      if($handle) {
        $this->fileColumns = explode('|', fgets($handle));
        fclose($handle);
      }
      
   // }    
    
    $this->tableColumns = array(
      'member_id',
      'client_id',
      'hard_bounce_date',
      'hard_bounce_status_code',
      'hard_bounce_smtp_response',
      'hard_bounce_apparently_from',
      'soft_bounce_date',
      'soft_bounce_status_code',
      'soft_bounce_smtp_response',
      'soft_bounce_apparently_from',
      'unsubscribe_date',
      'complaint_name',
      'complaint_date',
      'email',
      'source'
    );
    
  }
  
  public function executeProcessFile(sfWebRequest $request)
  {
    $this->forward404Unless($fields = $request->getParameter(('fields')));
    $this->forward404Unless($parseVars['fileName'] = $request->getParameter('file_name'));
    $this->forward404Unless($parseVars['campaignId'] = $request->getParameter('campaign_id'));
    $this->forward404Unless($fileType = $request->getParameter('file_type'));
    $parseVars['saveFields'] = array();
    foreach($fields as $key=>$field) {
      if($field != '' && $field != 'source') {
        $parseVars['saveFields'][$key] = $field;
      }
      elseif($field == 'source') {
        $parseVars['sourceField'] = $key;
      }
    }
    
    // if fields to save are not zero
    if(count($parseVars['saveFields']) > 0) {
      switch($fileType) {
        case 'selected':
          $this->parseSelected($parseVars);
      }
      
    }
    
  }

  private function parseSelected($parseVars)
  {
    $handle = fopen(getcwd().'/uploads/'.$parseVars['fileName'], 'r');
    if($handle) {
      $line = fgetcsv($handle);
      while (!feof($handle)) {
        $lineArray = fgetcsv($handle, 0, '|');
        //$lineArray = explode('|', $line);
        if($lineArray[$parseVars['sourceField']] != '') {
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = new EmailCampaignUserDetails();
            $emailCampaignUser->set('email_campaign_id', $parseVars['campaignId']);
            $emailCampaignUser->set('contant_information_id', $contact['id']);
            $tempSaveFields = $parseVars['saveFields'];
            unset($tempSaveFields[array_search('email', $tempSaveFields)]);
            //unset($parseVars['saveFields'][array_search('email', $parseVars['saveFields'])]);
            foreach($tempSaveFields['saveFields'] as $key=>$saveField) {
              if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                $emailCampaignUser->set($saveField, $lineArray[$key]);
              }
            }
            $emailCampaignUser->save();
            $emailCampaignUser->free(true);
            $emailCampaignUser = '';
            $conn = '';
            unset($emailCampaignUser, $conn);
          }
        }
      }
      
    }
  }

  private function parseHardBounce($parseVars)
  {
    $handle = fopen(getcwd().'/uploads/'.$parseVars['fileName'], 'r');
    if($handle) {
      $line = fgetcsv($handle);
      while (!feof($handle)) {
        $lineArray = fgetcsv($handle, 0, '|');
        //$lineArray = explode('|', $line);
        if($lineArray[$parseVars['sourceField']] != '') {
          $conn = Doctrine_Manager::connection();
          $contact = $conn->execute('SELECT id, email FROM contant_information WHERE email = "'.$lineArray[array_search('email', $parseVars['saveFields'])].'"')->fetch(PDO::FETCH_ASSOC);
          if($contact) {
            $emailCampaignUser = new EmailCampaignUserDetails();
            $emailCampaignUser->set('email_campaign_id', $parseVars['campaignId']);
            $emailCampaignUser->set('contant_information_id', $contact['id']);
            $tempSaveFields = $parseVars['saveFields'];
            unset($tempSaveFields[array_search('email', $tempSaveFields)]);
            //unset($parseVars['saveFields'][array_search('email', $parseVars['saveFields'])]);
            foreach($tempSaveFields['saveFields'] as $key=>$saveField) {
              if(isset($lineArray[$key]) && $lineArray[$key] != '') {
                $emailCampaignUser->set($saveField, $lineArray[$key]);
              }
            }
            $emailCampaignUser->save();
            $emailCampaignUser->free(true);
            $emailCampaignUser = '';
            $conn = '';
            unset($emailCampaignUser, $conn);
          }
        }
      }
      
    }
  }
  
}
